package com.aaa.vegetablemarketexpress.service.impl;

import com.aaa.vegetablemarketexpress.dao.CustomerDao;
import com.aaa.vegetablemarketexpress.dao.UserDao;
import com.aaa.vegetablemarketexpress.dao.UserRoleDao;
import com.aaa.vegetablemarketexpress.entity.Customer;
import com.aaa.vegetablemarketexpress.entity.Role;
import com.aaa.vegetablemarketexpress.entity.User;
import com.aaa.vegetablemarketexpress.service.CustomerService;
import com.aaa.vegetablemarketexpress.service.RoleService;
import com.aaa.vegetablemarketexpress.util.CustomException;
import com.aaa.vegetablemarketexpress.util.Page;
import com.aaa.vegetablemarketexpress.util.ResultStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @FileName: CustomerServiceImpl
 * @Description: 客户业务逻辑实现类
 * @Author: qxh
 * @CreateTime: 2025/9/10
 * @Version: 1.0.0
 */
@Service
public class CustomerServiceImpl implements CustomerService {
    @Resource
    private HttpSession session;

    @Resource
    private CustomerDao customerDao;
    @Resource
    private UserRoleDao userRoleDao;
    @Resource
    private RoleService roleService; // 注入角色服务

    /**
     * 根据客户ID查询客户信息
     * @param customerId
     * @return
     */
    @Override
    public Customer selectCustomerById(Long customerId) {
        return customerDao.selectCustomerById(customerId);
    }

    /**
     * 分页查询客户列表
     * @param page
     * @return
     */
    @Override
    public PageInfo selectCustomerList(Page<Customer> page) {
        if(page.getPageNo() == null || page.getPageNo() == 0 || page.getPageSize() == null || page.getPageSize() == 0){
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), ResultStatus.PARAM_ISNULL.getStatusMsg());
        }
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        Customer data = page.getData();
        return new PageInfo<>(customerDao.selectCustomerList(data));
    }

    /**
     * 添加客户
     * @param customer
     * @return
     */
    @Override
    public Customer insertCustomer(Customer customer) {
        // 设置默认值
        if (customer.getStatus() == null || customer.getStatus().isEmpty()) {
            customer.setStatus("0"); // 默认正常状态
        }
        if (customer.getAuditStatus() == null || customer.getAuditStatus().isEmpty()) {
            customer.setAuditStatus("0"); // 默认待审核状态
        }
        if (customer.getDelFlag() == null || customer.getDelFlag().isEmpty()) {
            customer.setDelFlag("0"); // 默认未删除
        }
        User loginUser = (User) session.getAttribute("userInfo");
        Long userId = loginUser.getUserId();
        customer.setUserId(userId); // 关联当前登录用户
        customer.setCreateBy(loginUser.getUserName());
        customer.setCreateTime(new Date());
        customer.setUpdateTime(new Date());
        customerDao.insertCustomer(customer);
        return customer;
    }

    /**
     * 修改客户
     * @param customer
     * @return
     */
    @Override
    public int updateCustomer(Customer customer) {
        // 验证客户ID是否存在
        if (customer.getCustomerId() == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "客户ID不能为空");
        }
        // 验证客户是否存在
        Customer existingCustomer = customerDao.selectCustomerById(customer.getCustomerId());
        if (existingCustomer == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "客户不存在");
        }
        customer.setUpdateTime(new Date());
        // 确保创建时间不被修改
        customer.setCreateTime(existingCustomer.getCreateTime());
        customer.setCreateBy(existingCustomer.getCreateBy());
        return customerDao.updateCustomer(customer);
    }

    /**
     * 删除客户（逻辑删除）
     * @param customerId
     * @return
     */
    @Override
    public int deleteCustomerById(Long customerId) {
        return customerDao.deleteCustomerById(customerId);
    }

    /**
     * 检查客户手机号是否唯一
     * @param customer
     * @return
     */
    @Override
    public String checkPhoneUnique(Customer customer) {
        int count = customerDao.checkPhoneUnique(customer.getPhone());
        if (count > 0) {
            return "1"; // 已存在
        }
        return "0"; // 不存在
    }

    /**
     * 审核客户
     * @param customer
     * @return
     */
    @Override
    @Transactional
    public int auditCustomer(Customer customer) {
        // 验证客户ID是否存在
        if (customer.getCustomerId() == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "客户ID不能为空");
        }
        // 验证客户是否存在
        Customer existingCustomer = customerDao.selectCustomerById(customer.getCustomerId());
        if (existingCustomer == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "客户不存在");
        }
        //  从Session获取登录用户信息（关键：自动填充审核人）
        User loginUser = (User) session.getAttribute("userInfo");
        if (loginUser == null) {
            throw new CustomException(ResultStatus.USER_NOT_LOGIN.getStatusCode(), "审核人未登录，请重新登录");
        }
        // 更新审核相关信息
        Customer updateCustomer = new Customer();
        updateCustomer.setCustomerId(customer.getCustomerId());
        updateCustomer.setAuditStatus(customer.getAuditStatus());// 前端传递的审核结果（1通过/2拒绝）
        updateCustomer.setAuditRemark(customer.getAuditRemark());// 前端传递的审核备注
        updateCustomer.setAuditBy(loginUser.getUserName()); // 从Session获取登录人姓名（审核人）
        updateCustomer.setAuditTime(new Date());// 自动生成当前审核时间
        updateCustomer.setUpdateTime(new Date()); // 更新时间同步
        // 如果审核通过，更新客户状态为正常
        if ("1".equals(customer.getAuditStatus())) {
            updateCustomer.setStatus("0");
            // 从 existingCustomer 中获取 userId
            Long userId = existingCustomer.getUserId();
            if (userId == null) {
                throw new CustomException(ResultStatus.DATA_INVALID.getStatusCode(), "客户未关联用户信息");
            }
            //  根据角色名称查询商家角色ID
            Role merchantRole = roleService.queryByRoleName("商家"); // 角色名称写死或配置在配置文件
            if (merchantRole == null) {
                throw new CustomException(ResultStatus.DATA_NOT_EXIST.getStatusCode(), ResultStatus.DATA_NOT_EXIST.getStatusMsg());
            }

            // 2. 关联角色
            Long[] roleIds = {merchantRole.getRoleId()};
            insertCustomerRoles(userId, roleIds);
        }

        return customerDao.updateCustomer(updateCustomer);
    }

    /**
     * 根据用户ID查询客户（商家）信息
     * @param userId 用户ID（从登录态获取）
     * @return
     */
    @Override
    public Customer selectCustomerByUserId(Long userId) {
        // 校验用户ID
        if (userId == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "用户ID不能为空");
        }
        // 调用DAO层查询（需在CustomerDao中新增对应方法）
        return customerDao.selectCustomerByUserId(userId);
    }

    /**
     * 为商家添加角色
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    public int insertCustomerRoles(Long userId, Long[] roleIds) {
        // 先删除该商家原有的角色关联
        userRoleDao.deleteUserRoleByUserId(userId);
        // 再插入新的角色关联（user_role表）
        if (roleIds != null && roleIds.length > 0) {
            return userRoleDao.batchUserRole(userId, roleIds);
        }
        return 1;
    }
    @Override
    public PageInfo selectCustomerListAndStatus(Page<Customer> page) {
        if(page.getPageNo() == null || page.getPageNo() == 0 || page.getPageSize() == null || page.getPageSize() == 0){
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), ResultStatus.PARAM_ISNULL.getStatusMsg());
        }
        PageHelper.startPage(page.getPageNo(), page.getPageSize());
        Customer data = page.getData();
        return new PageInfo<>(customerDao.selectCustomerListAndStatus(data));
    }

}
